#include <bits/stdc++.h>
using namespace std;

class Solution {
    queue<pair<int, int>> q;
    int m, n, cnt = 0;
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    bool vis[1010][1010] = {0};
public:
    int rotApple(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 2) q.push({i, j});
            }
        }
        while(!q.empty()) {
            cnt++;
            int sz = q.size();
            while(sz--) {
                auto [a, b] = q.front();
                q.pop();
                for(int k = 0; k < 4; k++) {
                    int x = dx[k] + a;
                    int y = dy[k] + b;
                    if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == 1) {
                        vis[x][y] = true;
                        q.push({x, y});
                    } 
                }
            }
        }
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1 && !vis[i][j]) return -1;
            }
        }
        return cnt-1;
    }
};